import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/home/detail/views/topic_view.dart';
import 'package:flutter_douban/main_page/home/nav_home_page.dart';
import 'package:flutter_douban/model/topic_model.dart';
import 'package:flutter_douban/tool_views/back_nav_btn.dart';
import 'package:flutter_douban/tool_views/nav_title_page.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class TopicListPage extends StatefulWidget {
  const TopicListPage({Key? key}) : super(key: key);

  @override
  _TopicListPageState createState() => _TopicListPageState();
}

class _TopicListPageState extends State<TopicListPage> {
  // 下拉刷新控制器
  EasyRefreshController? _easyRefreshController;
  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;
  // 列表数组模型
  List<TopicModel> _cookInfoList = TopicModelList([]).list;
  int page = 0;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String? errorMsg;

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
  }

  @override
  void dispose() {
    _easyRefreshController!.dispose();
    _scrollController!.dispose();
    super.dispose();
  }

  // 获取数据
  Future _getRecommendData({bool replace = true}) async {
    try {
      Map<String, dynamic> result = await HttpService.getHottopicData();
      TopicModelList infoList = TopicModelList.fromJson(result['list']);
      setState(() {
        page++;
        if (replace) {
          _cookInfoList = infoList.list;
        } else {
          _cookInfoList.addAll(infoList.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 0;
    await _getRecommendData();
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController!.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await _getRecommendData(replace: false);
    }
    // 结束加载
    _easyRefreshController!.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: BackNavBtn(),
        title: NavTitlePage(titleStr: '热门话题'),
      ),
      body: EasyRefresh(
        // 开启首次加载刷新
        firstRefresh: true,
        // 加载时的loading
        // firstRefreshWidget: PageFeedBack(firstRefresh: true).build(),
        // 空视图、异常视图
        // emptyWidget: PageFeedBack(
        //   loading: loading,
        //   error: error,
        //   empty: _songList.isEmpty,
        //   errorMsg: errorMsg,
        //   onErrorTap: () => _easyRefreshController.callRefresh(),
        //   onEmptyTap: () => _easyRefreshController.callRefresh(),
        // ).build(),
        header: CustomHeaderView(),
        footer: CustomFooterView(),
        controller: _easyRefreshController,
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        onRefresh: _onRefresh,
        child: SafeArea(
          child: Column(
            children: [
              ListView.builder(
                  controller: _scrollController,
                  itemCount: _cookInfoList.length,
                  shrinkWrap: true, //增加
                  itemBuilder: (BuildContext context, int index) {
                    return TopicView(
                      model: _cookInfoList[index],
                    );
                  }),
              Container(
                height: 60,
                child: Center(
                  child: Text(
                    '--  End  --',
                    style:
                        TextStyle(color: AppColors.qianTextColor, fontSize: 12),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
